package com.example.quiz.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;

public class ServiceManager extends Thread {
	private JSONObject data;
	private Handler handlerConnection;
	private String url = "http://192.168.25.18:8080/QuizServer/ServletLogin";
	private final int TAM_MAX_BUFFER = 20480;
 
	public ServiceManager(JSONObject data, Handler handlerConnection) {
		super();
		this.data = data;
		this.handlerConnection = handlerConnection;
 	}

	@Override
	public void run() {
		try {
		
			String resposta = sendJsonRequest( this.url, this.data );
			Message msg = new Message();
			msg.obj = resposta;
			this.handlerConnection.sendMessage(msg);

		} catch (Exception e) {
			Message msg = new Message();
			msg.obj = "TimeOut";
			this.handlerConnection.sendMessage(msg);
		}

		super.run();
	}

	private String sendJsonRequest(String url, JSONObject param)
			throws ClientProtocolException, IOException, JSONException 
	{		
		
	
		HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost( url );       
        httpPost.setHeader( "Content-type", "application/json" );
        
        //Atribuindo Parametros na requisicao
        HttpEntity bodyEntity = new StringEntity( param.toString() );
		httpPost.setEntity( bodyEntity);		
		
        //Fazendo a requis
        HttpResponse response = httpClient.execute( httpPost );
            
        //Obtendo resultado
        HttpEntity entity = response.getEntity();
		String result = null;
		if (entity != null) 
		{
			InputStream inStream = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader( inStream ), TAM_MAX_BUFFER);
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			result = sb.toString();

			inStream.close();
		}
		httpPost.abort();
		return result;
	}
}
